import 'package:flutter/material.dart';
import 'work_space_model.dart';

class WorkSpaceProvider with ChangeNotifier {
  
  bool isEditing = false;
  List<WorkSpaceModel> _list = [];
  List<WorkSpaceModel> get data => _list;
  List<WorkSpaceDetailModel> userMenusList;

  void setWorkSpaceData(List<WorkSpaceModel> data){
    _list = data;
    notifyListeners();
  }

  /// 开始编辑
  void editingWorkSpace(List<WorkSpaceModel> userMenus){

    isEditing = true;

    Map<String,WorkSpaceDetailModel> userMap = {};
    userMenus.forEach((WorkSpaceModel val){
      val.menus.forEach((WorkSpaceDetailModel userModel){
        userModel.status = EditStatus.delete;
        userMap[userModel.uuid] = userModel;
      });
    });

    for (WorkSpaceModel item in _list) {
      for (WorkSpaceDetailModel detailModel in item.menus) {
        if (userMap[detailModel.uuid] == null){
          detailModel.status = EditStatus.addition;
        }else{
          detailModel.status = EditStatus.delete;
        }
      }
    }

    userMenusList = userMenus.first.menus;
    _list.insertAll(0, userMenus);

    setWorkSpaceData(_list);

    notifyListeners();
  }

  /// 结束编辑
  void editedWorkSpace(){
    isEditing = false;
    _list.removeAt(0);
    for (WorkSpaceModel item in _list) {
      for (WorkSpaceDetailModel detailModel in item.menus) {
        detailModel.status = EditStatus.normal;
      }
    }
    notifyListeners();
  }

  /// 添加或删除
  void additionOrDelete(WorkSpaceDetailModel detailModel){

    WorkSpaceModel userMenus = _list.first;

    if (detailModel.status == EditStatus.delete){
      /// 删除
      for (var i = userMenus.menus.length - 1; i >= 0; i--) {
        WorkSpaceDetailModel model = userMenus.menus[i];
        if (model.uuid == detailModel.uuid) {
          userMenus.menus.removeAt(i);
        }
      }
      for (var i = 1; i < _list.length; i++) {
        WorkSpaceModel systemMenus = _list[i];
        systemMenus.menus.forEach((val){
          if(val.uuid == detailModel.uuid){
            val.status = EditStatus.addition;
          }
        });
      }
    }else{
      /// 添加
      userMenus.menus.add(detailModel);
      for (var i = 1; i < _list.length; i++) {
        WorkSpaceModel systemMenus = _list[i];
        systemMenus.menus.forEach((val){
          if(val.uuid == detailModel.uuid){
            val.status = EditStatus.delete;
          }
        });
      }
    }

    userMenusList = userMenus.menus;
    notifyListeners();
  }


  /// 设置用户模块
  void setUserMenus(List<WorkSpaceDetailModel> list){
    userMenusList = list;
    notifyListeners();
  }

}